import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_statistic.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_webview.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/login/user_model.dart';
import 'package:hxdj/mine/member_center/member_center_viewmodel.dart';
import 'package:provider/provider.dart';

class MemberCenterPage extends StatefulWidget {
  static String routeName = "/memberCenter";

  const MemberCenterPage({super.key});

  @override
  State<MemberCenterPage> createState() => _MemberCenterPageState();
}

class _MemberCenterPageState extends State<MemberCenterPage> {
  //viewModel
  MemberCenterViewModel? viewModel;

  @override
  void initState() {
    super.initState();
  }

  //导航栏
  Widget _buildHeader() {
    double topPadding = MediaQuery.of(context).padding.top;

    return SizedBox(
        height: 120 + topPadding + kToolbarHeight,
        child: Stack(
          children: [
            // 背景色
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 120 + topPadding + kToolbarHeight,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      // Color.fromRGBO(44, 44, 44, 0),
                      // Color.fromRGBO(44, 44, 44, 0.5),
                      MyColours.fromHex("1D1D1C"),
                      MyColours.fromHex("3C3636"),
                    ],
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                  ),
                ),
              ),
            ),
            Positioned(
                right: 0,
                left: 0,
                top: topPadding,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            alignment: Alignment.centerLeft,
                            child: GestureDetector(
                              onTap: () {
                                Navigator.pop(context);
                              },
                              child: Container(
                                color: Colors.transparent,
                                width: 30,
                                child: const Padding(
                                  padding: EdgeInsets.all(10.0),
                                  child: MyImage(imageName: "ic_white_black", width: 9, height: 15),
                                ),
                              ),
                            ),
                          ),
                        ),
                        //title
                        Expanded(
                          flex: 1,
                          child: Container(
                              alignment: Alignment.center,
                              child: const Text("会员中心", style: TextStyle(fontSize: 18, color: Colors.white))),
                        ),

                        Expanded(
                            flex: 1,
                            child: MyTapWidget(
                              onTap: () {
                                NavigatorUtils.pushParams(context, MyWebviewPage.routeName,
                                    params: {"title": "会员卡协议", "url": MyConstant.vipatUrl});
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Text("会员卡协议", style: TextStyle(fontSize: 12.sp, color: Colors.white)),
                                  Padding(
                                    padding: const EdgeInsets.all(5.0),
                                    child: MyImage(imageName: "ic_doubt", width: 10.w),
                                  ),
                                ],
                              ),
                            )),
                      ]),
                )),
            Positioned(left: 0, right: 0, bottom: 45, child: _buildPersonalInformation()),
          ],
        ));
  }

  //个人信息
  Widget _buildPersonalInformation() {
    MyGlobalViewModel globalViewModel = Provider.of<MyGlobalViewModel>(context, listen: false);
    UserModel? userModel = globalViewModel.userModel;
    UserDetailModel? userDetailModel = globalViewModel.userDetailModel;

    //名字 & 到期时间
    return Container(
      padding: EdgeInsets.only(left: 15.w, right: 15.w),
      child: Row(
        children: [
          //头像
          MyClipRect(imageUrl: userModel?.picUrl ?? "", width: 40.w),

          //名字 & 到期时间
          Container(
            padding: const EdgeInsets.only(left: 15),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(userModel?.nickName ?? "",
                        style: TextStyle(fontSize: 15.sp, color: Colors.white, fontWeight: FontWeight.bold)),
                    userDetailModel?.userData?.isVip == 1
                        ? Padding(
                            padding: EdgeInsets.only(left: 5.w),
                            child: const MyImage(imageName: "ic_vip_mine", width: 37.5, height: 15),
                          )
                        : Container(),
                  ],
                ),
                Text(userDetailModel?.userData?.isVip == 1 ? (userDetailModel?.userData?.vipEndTime ?? "") : "暂未开通会员",
                    style: TextStyle(fontSize: 11.sp, color: Colors.white)),
              ],
            ),
          ),
          const Spacer(),
          MyBorder(
            backgroundColor: MyColours.color242221,
            color: MyColours.color242221,
            radius: 15.h,
            width: 0,
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 9.h, horizontal: 25.w),
              child: Text(userDetailModel?.userData?.isVip == 1 ? "您正在享受特权" : "30万人已享受特权",
                  style: TextStyle(fontSize: 11.sp, color: Colors.white)),
            ),
          )
        ],
      ),
    );
  }

  //会员套餐
  Widget _buildPackage() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15.w),
            child: Text("会员套餐",
                style: TextStyle(fontSize: 15.sp, color: MyColours.textBlack, fontWeight: FontWeight.bold)),
          ),
          Container(
            margin: EdgeInsets.only(top: 12.h),
            color: MyColours.materialBg,
            height: 135.h,
            child: ListView.builder(
              itemCount: viewModel?.memberDetailModel?.detailData?.svip?.vipPriceList?.length,
              itemBuilder: (context, index) {
                VipPriceList? vipPriceModel = viewModel?.memberDetailModel?.detailData?.svip?.vipPriceList?[index];

                Color textColor = viewModel?.index == index ? MyColours.color752C06 : MyColours.textBlack;

                //折扣价格
                num discounts =
                    num.parse(vipPriceModel?.vipPriceIos ?? "1") * num.parse(vipPriceModel?.discounts ?? "1");

                return MyTapWidget(
                  onTap: () {
                    viewModel?.selectVip(index);
                  },
                  child: Container(
                    width: 125.w,
                    margin: EdgeInsets.only(right: 10.w),
                    color: MyColours.materialBg,
                    child: MyBorder(
                        width: 1,
                        color: MyColours.colorDFDFDF,
                        backgroundColor:
                            viewModel?.index == index ? MyColours.appMain.withOpacity(0.4) : MyColours.materialBg,
                        child: Column(children: [
                          // 套餐名称
                          Container(
                            padding: EdgeInsets.only(top: 27.h),
                            child: Text(vipPriceModel?.vipName ?? "",
                                style: TextStyle(fontSize: 12.sp, color: textColor, fontWeight: FontWeight.bold)),
                          ),

                          // 套餐价格
                          MyStatisticViewModel(
                            statistic: num.parse(vipPriceModel?.vipPriceIos ?? "0"),
                            statisticTS: TextStyle(fontSize: 26.sp, color: textColor, fontWeight: FontWeight.w700),
                            withName: '¥' " ",
                            withNameTS: TextStyle(fontSize: 15.sp, color: textColor, fontFamily: "Arial"),
                            statisticDecimalTS: TextStyle(color: textColor, fontSize: 14.sp),
                            prefix: '',
                            suffix: '',
                            toStringAsFixed: 0,
                          ).toRichText,
                          Container(
                            padding: EdgeInsets.only(bottom: 5.h),
                            child: Text("¥${discounts.toStringAsFixed(2)}",
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: viewModel?.index == index ? MyColours.color752C06 : MyColours.color9B9B9B,
                                  decoration: TextDecoration.lineThrough,
                                )),
                          ),

                          // 立省金额
                          Container(
                            padding: EdgeInsets.only(top: 10.h),
                            child: MyBorder(
                              backgroundColor: viewModel?.index == index ? MyColours.appMain : MyColours.line,
                              width: 0,
                              radius: 3,
                              color: viewModel?.index == index ? MyColours.appMain : MyColours.line,
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 25.w, vertical: 5.h),
                                child: Text("立省${discounts.toStringAsFixed(2)}元",
                                    style: TextStyle(
                                        fontSize: 11.sp,
                                        color:
                                            viewModel?.index == index ? MyColours.color752C06 : MyColours.color9B9B9B)),
                              ),
                            ),
                          ),
                        ])),
                  ),
                );
              },
              padding: EdgeInsets.only(left: 15.w),
              scrollDirection: Axis.horizontal,
            ),
          )
        ],
      ),
    );
  }

  //开通服务
  Widget _buildOpenService() {
    VipPriceList? vipPriceModel = viewModel?.vipPriceModel;
    String vipPriceIos = "";

    //折扣价格
    num discounts = num.parse(vipPriceModel?.vipPriceIos ?? "1") * (1 - num.parse(vipPriceModel?.discounts ?? "1"));

    vipPriceIos = discounts.toStringAsFixed(2);

    return Column(
      children: [
        //开通服务
        Container(
            margin: EdgeInsets.only(left: 10.w, right: 10.w),
            child: GestureDetector(
              onTap: () {
                if (viewModel?.isServiceAgreement == false) {
                  EasyLoading.showToast("请确认阅读并确认《付费会员服务协议》");
                  return;
                }
                debugPrint("点击了开通服务");
                viewModel?.openVip();
              },
              child: Container(
                  padding: EdgeInsets.symmetric(vertical: 15.w),
                  decoration: BoxDecoration(
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.circular(25.w),
                    gradient: LinearGradient(
                      colors: [
                        // Color.fromRGBO(44, 44, 44, 0),
                        // Color.fromRGBO(44, 44, 44, 0.5),
                        MyColours.fromHex("1D1D1C"),
                        MyColours.fromHex("3C3636"),
                      ],
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("￥$vipPriceIos 立即开通",
                          style: TextStyle(
                            fontSize: 15.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          )),
                    ],
                  )),
            )),

        //阅读政策
        Container(
          margin: EdgeInsets.only(left: 20.w, right: 10.w, top: 10.h),
          child: Row(
            children: [
              GestureDetector(
                onTap: () {
                  viewModel?.confirmServiceAgreement();
                },
                child: Padding(
                  padding: EdgeInsets.only(left: 10.w, right: 10.w),
                  child: MyImage(
                      imageName: (viewModel?.isServiceAgreement == true ? "ic_select" : "ic_un_select"), width: 15),
                ),
              ),
              RichText(
                  text: TextSpan(style: TextStyle(color: MyColours.textBlack, fontSize: 11.sp), children: [
                const TextSpan(text: '阅读并确认'),
                TextSpan(
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        NavigatorUtils.pushParams(context, MyWebviewPage.routeName,
                            params: {"title": "付费会员服务协议", "url": MyConstant.vipatUrl});
                      },
                    text: '《付费会员服务协议》',
                    style: const TextStyle(fontSize: 11, color: MyColours.color9B9B9B)),
              ])),
            ],
          ),
        ),
      ],
    );
  }

  //会员特权
  Widget _buildMemberPrivilege() {
    return //会员特权
        Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              margin: const EdgeInsets.only(left: 15),
              child: Row(
                children: [
                  const Text("会员特权",
                      style: TextStyle(fontSize: 15, color: MyColours.textBlack, fontWeight: FontWeight.bold)),
                  Padding(
                    padding: EdgeInsets.only(left: 6.w),
                    child: const MyImage(imageName: "ic_vip_privileges", width: 15),
                  ),
                ],
              )),
          Container(
            margin: const EdgeInsets.only(top: 15),
            color: Colors.white,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(children: [
                  const MyImage(imageName: "ic_discount", width: 42),
                  Container(
                    padding: const EdgeInsets.only(top: 10),
                    child: const Text("专属折扣", style: TextStyle(fontSize: 11, color: MyColours.textBlack)),
                  ),
                ]),
                Column(children: [
                  const MyImage(imageName: "ic_Identity_identification", width: 42),
                  Container(
                    padding: const EdgeInsets.only(top: 10),
                    child: const Text("身份标识", style: TextStyle(fontSize: 11, color: MyColours.textBlack)),
                  ),
                ]),
                Column(children: [
                  const MyImage(imageName: "ic_quick_refund", width: 42),
                  Container(
                    padding: const EdgeInsets.only(top: 10),
                    child: const Text("极速退款", style: TextStyle(fontSize: 11, color: MyColours.textBlack)),
                  ),
                ]),
                Column(children: [
                  const MyImage(imageName: "ic_order_acceptance", width: 42),
                  Container(
                    padding: const EdgeInsets.only(top: 10),
                    child: const Text("优先接单", style: TextStyle(fontSize: 11, color: MyColours.textBlack)),
                  ),
                ])
              ],
            ),
          )
        ],
      ),
    );
  }

  _buildBody() {
    switch (viewModel?.state) {
      case ViewState.loading:
        return const MyLoadingWidget();

      default:
        return Container(
            color: Colors.white,
            child: Column(children: [
              //导航栏
              _buildHeader(),

              //会员套餐
              _buildPackage(),

              //开通服务
              _buildOpenService(),

              //会员特权
              _buildMemberPrivilege(),
            ]));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BasePage<MemberCenterViewModel>(
        onModelReady: (model) {
          // 页面初始化完成后的回调
          viewModel = model;
          model.requestData();
        },
        viewModel: MemberCenterViewModel(),
        builder: (BuildContext context, MemberCenterViewModel? model, Widget? child) {
          return Scaffold(body: _buildBody());
        });
  }
}
